package com.aggregate.pay.swiftpass.support.client;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import com.aggregate.pay.swiftpass.bean.NotifyData;
import com.aggregate.pay.swiftpass.support.Client;
import com.aggregate.pay.swiftpass.support.Factory;
import com.aggregate.pay.swiftpass.support.FieldMap;
import com.aggregate.pay.swiftpass.support.Merch;
import com.aggregate.pay.swiftpass.support.Tool;
import com.aggregate.pay.swiftpass.support.utils.XML;
import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 微信扫码支付接口
 * @author Moyq5
 * @date 2019年2月19日
 */
public class Notify implements Client<HttpServletRequest, NotifyData> {
	public static final String CHARSET = "UTF-8";
	
	public Notify(Merch merch) {
		
	}
	@Override
	public NotifyData execute(HttpServletRequest req) {
		log.debug("支付回调 -> 请求地址：{}", req.getRequestURI());
		log.debug("支付回调 -> 请求参数：{}", req.getQueryString());
		NotifyData data = new NotifyData();
		try {
			InputStream is = req.getInputStream();
			byte[] b = new byte[1024];
			int i;
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			while((i=is.read(b)) != -1) {
				os.write(b, 0, i);
			}
			is.close();
			os.close();
			String reqBody = os.toString(CHARSET);
			
			log.debug("支付回调 -> 请求报文：{}", reqBody);
			
			data = XML.toObject(reqBody, NotifyData.class);
			if (data.getStatus() == 0) {
				FieldMap map = XML.toObject(reqBody, new TypeReference<FieldMap>(){});
				/*
				if (!Tool.md5Sign(map, merch.md5Key()).equals(data.getSign())){
					throw new Exception("通知内容签名验证失败");
				}
				*/
				if (!Tool.rsaVerify(map, Factory.getConfig().pubKey())) {
					throw new Exception("通知内容签名验证失败");
				}
				
			}
		} catch (Exception e) {
			log.error("支付回调 -> 处理失败", e);
			data.setStatus(-1);
			data.setMessage("本地错误：" + e.getMessage());
		}
		return data;
	}

}
